<?php
/**
 * Created by PhpStorm.
 * User: stc17
 * Date: 2020/3/7
 * Time: 9:01
 */

namespace App\Listener;

use SwoStar\Event\Listener;
use SwoStar\Server\WebSocket\Connections;
use SwoStar\Server\WebSocket\WebSocketServer;

use Swoole\Coroutine\Http\Client;

class WSMessageFrontListener extends Listener
{
    protected $name='ws.message.front';

    public function handler(WebSocketServer $swoStarServer=null, $swooleServer=null,$frame=null)
    {
       /*消息格式
       {
        'method'=>执行操作
       'msg'=>消息
       }
       */

       $data=\json_decode($frame->data,true);
       $this->{$data['method']}($swoStarServer, $swooleServer,$data,$frame->fd);

    }

    //imserver接收客户端广播 并 向route服务器转发广播
    protected function serverBroadcast(WebSocketServer $swoStarServer, $swooleServer,$data,$fd)
    {
        $config=$this->app->make('config');

        $cli=new Client($config->get('server.route.server.host'),$config->get('server.route.server.port'));
        if($cli->upgrade('/')){
            $cli->push(\json_encode([
                'method'=>'routeBroadcast',
                'msg'=>$data['msg']
            ]));
        }
    }

    //imserver接收route服务器的广播， 然后群发
    protected function routeBroadcast(WebSocketServer $swoStarServer, $swooleServer,$data,$fd)
    {
        $dataAck=[
            'method'=>'ack',
            'msg_id'=>$data['msg_id'],
        ];
        dd($dataAck);
        $swooleServer->push($fd,\json_encode($dataAck));
      //  dd($data['data'], 'server 中的 routeBroadcast');
        $swoStarServer->sendAll(json_encode($data['data']));
    }
    
    //imserver接收客户端私聊信息
    protected function privateChat(WebSocketServer $swoStarServer, $swooleServer,$data,$fd)
    {
        //1.获取私聊id
        $clientId=$data['clientId'];

        //2.从redis获取对应服务器信息
        $clientIMServerInfoJson=$swoStarServer->getRedis()
            ->hGet($this->app->make('config')->get('server.route.jwt.key'),$clientId);
        $clientIMServerInfo=json_decode($clientIMServerInfoJson,true);
        dd($clientIMServerInfo,'接收方的服务器信息');
        //3.指定发送
        $request = Connections::get($fd)['request'];
        $token = $request->header['sec-websocket-protocol'];
        $clientIMServerUrl=explode(":",$clientIMServerInfo['serverUrl']);

        $swoStarServer->send($clientIMServerUrl[0],$clientIMServerUrl[1],[
            'method'=>'forwarding',
            'msg'=>$data['msg'],
            'fd'=>$clientIMServerInfo['fd'],
        ],[
            'sec-websocket-protocol' => $token
        ]);
    }

    //imserver转发私聊信息
    protected function forwarding(WebSocketServer $swoStarServer, $swooleServer,$data,$fd)
    {
        $swooleServer->push($data['fd'],json_encode(['msg'=>$data['msg']]));
    }
}